package com.zhanglijie.theory.workthread;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/8/13 0013 18:36
 */
public class ContractFolder {
    private static final int MAX = 100;
    //合同队列（任务队列）
    private Contract[] contractQueue;
    //施工队（执行线程队列）
    private final WorkerThread[] threadPool;
    private int count;
    private int head;
    private int tail;
    public ContractFolder( int poolSize){
        this.contractQueue = new Contract[MAX];
        this.head = 0;
        this.tail = 0;
        this.count = 0;
        this.threadPool = new WorkerThread[poolSize];
        for (int i = 0; i < poolSize; i++) {
            WorkerThread contractorThread = new WorkerThread("施工队" + i, this);
            threadPool[i] = contractorThread;
        }
    }
    public void startWorkers(){
        for (int i = 0; i < threadPool.length; i++) {
            threadPool[i].start();
        }
    }

    public synchronized void putContract(Contract contract) throws InterruptedException {
        while(count>=contractQueue.length){
            wait();
        }
        contractQueue[tail] = contract;
        tail = ((tail+1)%contractQueue.length);
        count++;
        notifyAll();
    }

    public synchronized Contract getContract() throws InterruptedException {
        while(count<=0){
            wait();
        }
        if(count==0){
            wait();
        }
        Contract contract = contractQueue[head];

        head = ((head+1)%contractQueue.length);//这个可以替换上面的多行注释
        count--;
        notifyAll();
        return contract;
    }
}
